/*
 * CS_WRITE_MAIL.cpp
 *
 *  Created on: 2013. 8. 19.
 *      Author: the2
 */

#include "../../Command.h"
#include "../../User.h"
#include "../../NLogic/Bag.h"
#include "../../NLogic/Item.h"
#include "../../NLogic/Function.h"
#include "../../NLogic/MailBox.h"
#include "../../NLogic/Static.h"
#include "../../NResource/Static.h"

namespace ProjectZ { namespace NCommand {

void Command::CS_WRITE_MAIL(User * pUser, ::Network::Packet * pPacket)
{
/*	CS_WRITE_MAIL			0x1200
	{
		u32				u32user_seq;				// 받는 사람 Seq
		u64				u64item_seq;				// 아이템 seq
		u8				u8bag_Type;				// 가방 타입
		str				strmail_message;			// 편지 내용
	}

	//편지 보내기
	SC_WRITE_MAIL			0x1201
	{
		s16				ack;							// 1: 보내기 성공, -1: 실패, -2: 없는 아이디
	}*/

	PREPARE_PACKET;

	uint32_t recvUserSeq	= 0;
	uint64_t itemSeq		= 0;
	uint8_t bagType			= 0;
	Toolkit::Str<180> message;

	*pPacket >> recvUserSeq >> itemSeq >> bagType >> message;

	if (false == NLogic::NFunction::IsRegisterUser(recvUserSeq))
	{
		::Network::Packet * pAck = ::Network::GETPACKETPOOL()->SEND_NEW();
		*pAck << static_cast<int16_t>(ACK_NOT_EXIST_USER);
		pAck->MakePacket(CMD_SC_WRITE_MAIL);
		pUser->Send(pAck);
		return;
	}

	NLogic::Bag * pBag		= NULL;
	NLogic::Item * pItem	= NULL;

	if (itemSeq > 0)
	{
		if (true == NResource::Static::Instance().GetContentsOpenResource()->IsOpen(static_cast<int>(ContentsOpen::CHINA_CONTENTS)))
		{
			NResource::VIPResource::Data & vipData = NResource::Static::Instance().GetVIPResource()->GetData();

			if (vipData._VIP2_VP > pUser->GetUserInfo().reserve4)
			{
				::Network::Packet * pAck = ::Network::GETPACKETPOOL()->SEND_NEW();
				*pAck << static_cast<int16_t>(ACK_NOT_VIP2);
				pAck->MakePacket(CMD_SC_WRITE_MAIL);
				pUser->Send(pAck);
				return;
			}
		}

		pBag	= pUser->GetBag(static_cast<INVEN_BAG_TYPE>(bagType));
		if (NULL == pBag)
		{
			DEBUGLOG("CS_WRITE_MAIL : pBag is NULL!!");
			return;
		}

		pItem = pBag->GetItem(itemSeq);
		if (NULL == pItem)
		{
			DEBUGLOG("CS_WRITE_MAIL : pItem is NULL!!");
			return;
		}
	}

	NLogic::MailBox::Mail::Data clsData;

	clsData.send_user_seq		= pUser->GetUserSeq();
	clsData.send_user_nickname	= pUser->GetUserInfo().nickname.c_str();
	clsData.send_user_imageurl	= pUser->GetUserInfo().profile_url.c_str();
	clsData.recv_user_seq		= recvUserSeq;
	clsData.message				= message.c_str();

	if (NULL != pItem)
	{
		clsData.gift_status		= EM_GIFT_ITEM;
		clsData.item			= pItem->GetData();
	}

	if (false == NLogic::NFunction::SendMail(pUser, clsData))
	{
		DEBUGLOG("CS_WRITE_MAIL : false == NLogic::NFunction::SendMail");
		return;
	}

	if (NULL != pItem)
	{
		pBag->PopItem(itemSeq);
		pItem->DeleteDatabaseItemInfo(NLogic::Item::ItemStatus::EM_ITEM_STATUS_SEND_MAIL);
	}

	::Network::Packet * pAck = ::Network::GETPACKETPOOL()->SEND_NEW();
	*pAck << static_cast<int16_t>(ACK_OK);
	pAck->MakePacket(CMD_SC_WRITE_MAIL);
	pUser->Send(pAck);
}

} /*NCommand*/ } /*ProjectZ*/
